<?php

namespace Hookrock\Admin\Console;

use Illuminate\Console\Command;

class InstallsCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $signature = 'admin:install';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install the admin package';

    /**
     * Install directory.
     *
     * @var string
     */
    protected string $directory = '';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->initAdminDirectory();
    }

    /**
     * Initialize the admin directory.
     *
     * @return void
     */
    protected function initAdminDirectory(): void
    {
        $this->setDirectory();
        if (is_dir($this->directory)) {
            $this->warn("{$this->directory} directory already exists !");
        } else {
            $this->makeDir('/');
            $this->line('<info>Admin directory was created:</info> ' . str_replace(base_path(), '', $this->directory));
        }

        if (!is_dir($this->directory . '/Controllers')) {
            $this->makeDir('Controllers');
            $this->createHomeController();
            $this->createRouter();
        }
    }

    /**
     * Create HomeController.
     *
     * @return void
     */
    public function createHomeController(): void
    {
        $homeController = $this->directory . '/Controllers/HomeController.php';
        $contents = $this->getStub('HomeController');

        $this->laravel['files']->put(
            $homeController,
            str_replace(
                ['DummyNamespace', 'MetricsNamespace'],
                [$this->namespace('Controllers'), $this->namespace('Metrics\\Examples')],
                $contents
            )
        );
        $this->line('<info>HomeController file was created:</info> ' . str_replace(base_path(), '', $homeController));
    }

    /**
     * Get stub contents.
     *
     * @param $name
     * @return string
     */
    protected function getStub($name): string
    {
        return $this->laravel['files']->get(__DIR__ . "/stubs/$name.stub");
    }

    /**
     * Get the base namespace for admin controllers.
     * 
     * @param string|null $subNamespace 要附加的子命名空间（如 'Models'）
     * @return string
     */
    protected function namespace(?string $subNamespace = null): string
    {
        $controllerNamespace = config('admin.route.namespace', 'App\Admin\Controllers');

        $baseNamespace = rtrim($controllerNamespace, '\\');
        if (str_ends_with($baseNamespace, '\\Controllers')) {
            $baseNamespace = substr($baseNamespace, 0, -12);
        }

        $baseNamespace = trim($baseNamespace, '\\') . '\\';

        if ($subNamespace) {
            return $baseNamespace . trim($subNamespace, '\\');
        }

        return $baseNamespace;
    }


    /**
     * make directory.
     * @param string $path 路径
     * @return void
     */
    protected function makeDir(string $path = ''): void
    {
        $this->laravel['files']->makeDirectory("{$this->directory}/$path", 0755, true, true);
    }

    /**
     * set directory.
     * @return void
     */
    protected function setDirectory(): void
    {
        $this->directory = config('admin.directory');
    }

    /**
     * Create router.
     * @return void
     */
    protected function createRouter(): void
    {
        $router = $this->directory . '/router.php';
        $contents = $this->getStub('router');
        $this->laravel['files']->put(
            $router,
            $contents
        );
        $this->line('<info>router file was created:</info> ' . str_replace(base_path(), '', $router));
    }
}
